let _Vue = null

class VueRouter {
  static install(Vue) {
    // 判断插件是否安装
    if (VueRouter.install.installed) return

    VueRouter.install.installed = true
    // 把Vue的构造函数记录在全局
    _Vue = Vue
    // 把创建的Vue的实例传入的router对象注入到Vue实例 Vue.mixin
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router;
        }
      }
    })
  }

  constructor(options) {
    this.options = options;
    // 路由映射组件
    this.routeMap = {}
    this.data = _Vue.observable({
      current: '/'
    })
    this.init()
  }

  init() {
    this.createRouteMap()
    this.initComponent(_Vue)
    this.initEvent()
  }

  createRouteMap() {
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  initComponent(Vue) {
    Vue.component('router-link', {
      props: {
        to: String,
      },
      render(h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.handleClick
          }
        }, [this.$slots.default])
      },
      methods: {
        handleClick(e) {
          if (this.options.name === 'history') {
            history.pushState({}, '', this.to)
            this.$router.data.current = this.to
          } else {
            // hash 路由
            window.location.hash = this.to
          }
          e.preventDefault()
        }
      }
    })
    const self = this
    // 从路由映射对象中获取对应的渲染组件
    Vue.component('router-view', {
      render(h) {
        const Component = self.routeMap[self.data.current]
        return h(Component)
      }
    })
  }

  // 浏览器前进和后退事件
  initEvent() {
    if (this.options.name === 'history') {
      window.addEventListener('popstate', () => {
        this.data.current = window.location.pathname
      })
    } else {
      window.addEventListener('hashchange', () => {
        this.data.current = window.location.hash.replace('#', '')
      })
    }
  }
}

export default VueRouter
